<?php
class Mysql{
	public $table = '';//把类中方法的公有参数，提取为属性
	public $where = array();//条件
	public $offset = 0;//下标开始
	public $limit = 0;
	public $sel = '*';
	public $join = array();
	
	/**
	*获取列表
	*/
	public function getList(){
		$joinStr = $this->getJoin($this->join);
		$list = array();
		$keyword  = $this->getKeyWord();
		$sql = "select ".$this->sel." from ".$this->table;
		$sql.=!empty($joinStr)?$joinStr:'';
		$sql.=!empty($keyword)?' where '.$keyword:'';//如果keyword不为空，组装为sql语句
		$sql.=!empty($this->limit)?' limit '.$this->offset.",".$this->limit:'';//如果limit不为0，组装为sql语句
		$query = mysql_query($sql);//获取结果集，当sql语句执行失败时返回false，否则返回结果集
		while($data = mysql_fetch_assoc($query))  //while循环资源
		{     
			$list[] = $data;           //组装数组
		} 
		return $list;
		//print_r($list);exit;
	}
	/**
	 * 获取一行
	 */

	 public function getOne(){
		$keyword = '';
		$keyword  = $this->getKeyWord();
		$sql = "select * from ".$this->table;//根据ID查找
		$sql.=!empty($keyword)?' where '.$keyword:'';//如果keyword不为空，组装为sql语句
		$query = mysql_query($sql);
		$result = mysql_fetch_assoc($query);//获取当id的数据
		return $result;
	}
	 
	/**
	 * 插入
	 */

	public function create($arr){
		$k = '';
		$v = '';
		foreach($arr as $key=>$value){
			$k.=$key.",";
			$v.="'".$value."',";
		}
		
		$k = substr($k,0,-1);//截取从第0个到最后一个（-1）=>字段字符串
		
		$v = substr($v,0,-1);
		//print_r($k);exit;
		$sql = "insert into ".$this->table."(".$k.") values(".$v.")";
		
		$query = mysql_query($sql);
		if($query){
			return true;
		}
		return false;
	 }
	 
	 /**
	 *修改编辑
	 */
	 public function update($arr){
		$updateStr = '';
		foreach($arr as $key=>$value){
			$updateStr.=$key.'="'.$value.'",';
		}
		$updateStr = substr($updateStr,0,-1);
		//print_r($updateStr);
		$sql = "update ".$this->table." set ".$updateStr."where id = ".$arr['id'];
		//print_r($sql);exit;
		$query = mysql_query($sql);
		if($query){
			return true;
		}
		return false;
	 }
	 
	 /**
	 *获取关键字
	 */
	protected function getKeyWord(){
		$keyword = '';
		if(!empty($this->where)){
			//组装where条件
			foreach($this->where as $key=>$value){
				$keyword.=$key.'= "'.$value.'" and ';
			}
			$keyword = substr($keyword,0,-4);//取消最后一个and
			
		}
		return $keyword;
		
	}
		
	/**
	 * 拼接链接
	 */
	protected  function getJoin($joinArr){
		$join = '';
		if(!empty($joinArr)){
			$join = '';
			switch($joinArr['join']){
				case 'left':
					$join.=' left join ';
					break;
				case 'inner':
					$join.=' inner join ';
					break;
				default: 
					$join.=' join ';
					break;
			};
			$join.=$joinArr['tab'];//'left join 12_type'
			$join.=' on '.$this->table.'.'.$joinArr['left_on'].' = '.$joinArr['tab'].'.'.$joinArr['right_on'];
		}
		return $join;
	 }
}